<%-- 
    Document   : SystemUserMgmt
    Created on : Dec 13, 2011, 2:26:31 PM
    Author     : karennyq
--%>

<%@page import="java.util.HashMap"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>System User Management</title>
        <%@include file = "global/admin_include.jsp" %>
        <%
            HashMap am = new HashMap();
            Object obj = request.getSession().getAttribute("accessMap");
            if (obj == null) {
                response.sendRedirect("../admin.jsp");
            } else {
                am = (HashMap) obj;
                if (am.get("G").equals("false")) {
                    response.sendRedirect("accessDenied.jsp");
                }
            }
        %>
        <script type="text/javascript">
            var roles=null;
            
            $(document).ready(function(){
                $('#dd').dialog({modal:true});
                $('#dd').dialog('close');
                
                $('#loading_img').hide();
                $('#form_buttons').show();
                
                loadRoleDropDown();
                
                $('#tt').datagrid({
                    onBeforeEdit:function(index,row){
                        row.editing = true;  
                        updateActions(); 
                    },  
                    onAfterEdit:function(index,row){  
                        if (row.name == "" || row.email == ""){
                            alertMsgStr("Edit System User", "All fields are required", "error");
                            $('#tt').datagrid('beginEdit', index);
                            
                        } else if (!validateEmail(row.email)){
                            alertMsgStr("Edit System User", "Invalid email", "error");
                            $('#tt').datagrid('beginEdit', index);
                            
                        } else {
                            row.editing = false; 
                            $.ajax({
                                type: "POST",
                                url: "../SystemUserServlet",
                                data: "action=updateSystemUser"
                                    +"&updated_email="+row.email
                                    +"&updated_name="+row.name
                                    +"&sys_user_id="+row.sys_user_id
                                    +"&updated_role="+row.role_name,
                                dataType: "json",
                                cache: false,
                                success: function(data){
                                    if((data.type!='error')){
                                        $('#tt').datagrid('reload');
                                    }else{
                                        $('#tt').datagrid('beginEdit', index);
                                    }
                                    alertMsg(data);
                                }
                            }); 
                            updateActions();
                        }       
                    },  
                    onCancelEdit:function(index,row){  
                        $('#tt').datagrid('reload');
                    }
                });                
            }); 
            
            function validateEmail(elementValue){  
                var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
                return emailPattern.test(elementValue);  
            }
            
            function createSysUser(){
                var role = $('#user_role').combobox('getValue');
                var name = $("#user_name").val();
                var email = $("#user_email").val();
                
                if (role == "" || name == "" || email == "") {
                    alertMsgStr("New System User", "All fields are required", "error");
                } else if (!validateEmail(email)) {
                    alertMsgStr("New System User", "Invalid email", "error");
                } else {
                    parent.$('#resetPwd-dialog').dialog('open');
                    $('#dd').dialog('close');
                            
                    $.ajax({
                        type: "POST",
                        url: "../SystemUserServlet",
                        data: "action=createSysUser"
                            + "&user_role=" + role
                            + "&user_name=" + name
                            + "&user_email=" + email,
                        dataType: "json",
                        cache: false,
                        success: function(data){
                            parent.$('#resetPwd-dialog').dialog('close');
                            if((data.type!='error')){
                                $('#dd').dialog('close'); 
                                $('#tt').datagrid('reload');
                            }else{
                                $('#dd').dialog('open'); 
                            }
                            
                            if(data.type=='email-error'){
                                $('#dd').dialog('close'); 
                                alertMsgStr(data.title, data.content, "error")
                                $('#tt').datagrid('reload');
                            }else{
                                alertMsg(data);
                            }
                        }
                    });
                }
            }
            
            function loadRoleDropDown(){
                $('#user_role').combobox({  
                    url:'../SystemUserServlet?action=loadRoleDropDown',  
                    valueField:'id',  
                    textField:'text',
                    editable:false
                    //formatter:comboboxFomatter
                });
            }
            
            function openDD(){
                $('#dd').dialog('open');
                $('#user_name').val("");
                $('#user_email').val("");
                $('#user_role').combobox('setValue','');
            }

            function closeDD(formId,content){
                $('#dd').dialog('close'); 
            }
            
            function formatRole(value,rowData,rowIndex){
                return value;       
            }
            
            function formatActionResetPwd(value,rowData,rowIndex){
                return '<input type="button" onclick="resetPwd('+rowData.sys_user_id+');" value="Reset Password"/>'; 
            }
            
            function formatActions(value, row, index){
                if (row.editing){  
                    var s = '<input type="button" onclick="saverow('+index+')" value="Save"/> ';  
                    var c = '<input type="button" onclick="cancelrow('+index+')" value="Cancel"/>';  
                    return s+c;  
                } else {  
                    var e = '<input type="button" onclick="editrow('+index+')" value="Edit" /> ';
                    var d = '<input type="button" onclick="deleteSysUser('+row.sys_user_id+');" value="Delete"/>';
                    return e+d;    
                }
            }
            
            function updateActions(){  
                var rowcount = $('#tt').datagrid('getRows').length;  
                for(var i=0; i<rowcount; i++){ 
                    $('#tt').datagrid('updateRow',{  
                        index:i,  
                        row:{actions:''}  
                    });  
                }  
            }  
            
            function editrow(index){  
                $('#tt').datagrid('beginEdit', index);  
            }  
             
            function saverow(index){  
                $('#tt').datagrid('endEdit', index);  
            }
            
            function cancelrow(index){  
                $('#tt').datagrid('cancelEdit', index);  
            }
            
            function deleteSysUser(sys_user_id){
                window.parent.$.messager.confirm("Confirm", "Delete System User ID: " + sys_user_id + "?", function(r){
                    if (r){
                        $.ajax({
                            type: "POST",
                            url:"../SystemUserServlet",
                            data: "action=deleteSysUser"
                                +"&sys_user_id="+sys_user_id,
                            dataType: "json",
                            cache: false,
                            success: function(data){
                                if(data.type!='error'){ 
                                    $('#tt').datagrid('reload');
                                }
                                alertMsg(data);
                            }
                        });
                    }
                });
            }
            
            function resetPwd(sys_user_id){
                window.parent.$.messager.confirm("Confirm", "Reset password for System User ID: " + sys_user_id + "?", function(r){
                    if (r){
                        parent.$('#resetPwd-dialog').dialog('open');
                        $.ajax({
                            type: "POST",
                            url:"../SystemUserServlet",
                            data: "action=resetPwd"
                                +"&sys_user_id="+sys_user_id,
                            dataType: "json",
                            cache: false,
                            success: function(data){
                                parent.$('#resetPwd-dialog').dialog('close');
                                alertMsg(data); 
                            }
                        });
                    }
                });
            }
        </script>
    </head>
    <body>
        <div style="border-bottom:1px solid #ccc"><h2>System User Management</h2></div> 
        <br/>
        <div id="tb" style="padding:5px;height:auto">
            <table width="100%">
                <tr>
                    <td align="right"><input type="button" value="New System User" onclick="openDD()"/></td>
                </tr>
            </table>
        </div>  
        <div style="height:450px">
            <table id="tt" class="easyui-datagrid" fit="true"
                   url="../SystemUserServlet?action=loadTable"   
                   toolbar="#tb"  
                   singleSelect="true" fitColumns="true" pagination="true"
                   rownumbers="false">  
                <thead>  
                    <tr> 
                        <th field="sys_user_id" width="5%" sortable="true">ID</th>  
                        <th field="name" 
                            editor="{
                            type:'text'
                            }" 
                            width="25%" sortable="true">Name</th>
                        <th field="email" 
                            editor="{
                            type:'text'
                            }"  
                            width="25%" sortable="true">Email</th>
                        <th field="role_name" width="15%" 
                            editor="{  
                            type:'combobox', 
                            options:{  
                            valueField:'text',  
                            textField:'text',
                            url:'../SystemUserServlet?action=loadUpdateRoleDropDown',  
                            required:true} 
                            }" formatter="formatRole">Role</th> 
                        <th field="actionResetPwd" width="15%" align="center" formatter="formatActionResetPwd"></th>
                        <th field="actions" width="15%" align="center" formatter="formatActions"></th>
                    </tr>  
                </thead>  
            </table>
        </div>
        <div id="dd" title="New System User" style="width:215px; height:200px">
            <table>
                <tr>
                    <td colspan="2"><font color="red">All fields are required</font><br/><br/></td>
                </tr>
                <tr>
                    <td>Name:</td>
                    <td><input id="user_name" name="user_name" type="text"/></td>
                </tr>
                <tr>
                    <td>Email:</td>
                    <td><input id="user_email" name="user_email" type="text"/></td>
                </tr>
                <tr>
                    <td>Role:</td>
                    <td><select id="user_role" name="user_role" panelHeight="auto"></select></td>
                </tr>
                <tr id ="form_buttons">
                    <td colspan="2" align="center">
                        <br/>
                        <input type="button" onclick="createSysUser()" value="Create" />
                        <input type="button" onclick="closeDD()" value="Cancel" />
                    </td>
                </tr>
                <tr>
                    <td id="loading_img" colspan="2" align="center">
                        <br/>
                        <img src="./css/images/ajax-loader.gif"/>Loading... Please wait!<br/>
                    </td>
                </tr>
            </table>
        </div>
    </body>
</html>
